<template>
  <div class="llm-history-container">
    <div class="history-header">
      <h4>历史记录</h4>
      <el-button type="text" @click="clearHistory">清空</el-button>
    </div>
    <el-scrollbar class="history-list">
      <div v-if="history.length === 0" class="empty-state">
        <p>暂无历史记录</p>
      </div>
      <div v-else>
        <div v-for="item in history" :key="item.id" class="history-item">
          <p class="command-text">{{ item.command }}</p>
          <div class="item-footer">
            <span class="timestamp">{{ item.time }}</span>
            <div class="actions">
              <el-button type="text" size="small" @click="regenerate(item)">重新生成</el-button>
              <el-button type="text" size="small" @click="deleteItem(item.id)">删除</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const history = ref([]);

onMounted(() => {
  loadHistory();
});

const loadHistory = () => {
  // 模拟从localStorage加载
  const savedHistory = localStorage.getItem('llm_history');
  if (savedHistory) {
    history.value = JSON.parse(savedHistory);
  } else {
      // 添加一些mock数据
      history.value = [
          {id: 1, command: '预处理 -> 降维', time: '2023-10-05 10:20:00'},
          {id: 2, command: '标准化然后导出CSV', time: '2023-10-04 15:00:00'}
      ]
  }
};

const saveHistory = () => {
  localStorage.setItem('llm_history', JSON.stringify(history.value));
};

const clearHistory = () => {
  ElMessageBox.confirm('确定要清空所有历史记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    history.value = [];
    saveHistory();
    ElMessage.success('历史记录已清空');
  });
};

const regenerate = (item) => {
  // 在实际应用中，这里会触发一个事件，将指令填充回输入框
  ElMessage.info(`将重新生成指令: "${item.command}"`);
};

const deleteItem = (id) => {
  history.value = history.value.filter(item => item.id !== id);
  saveHistory();
  ElMessage.success('记录已删除');
};
</script>

<style scoped>
.llm-history-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}
.history-header h4 {
  margin: 0;
}
.history-list {
  flex-grow: 1;
}
.empty-state {
  text-align: center;
  color: #909399;
  padding-top: 50px;
}
.history-item {
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}
.command-text {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
}
.item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}
</style>
